package com.tang.thepath;


import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import com.tang.thepath.db.DefaultDBHelper;
import com.tang.thepath.util.LogUtil;
import com.tang.thepath.util.StorageType;
import com.tang.thepath.util.StorageUtil;

public class App extends Application {

    private DefaultDBHelper dbHelper;

    public static Context getContext() {
        return context;
    }

    private static Context context;
    public static final String TAG = "App";


    public class NetworkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            NetworkInfo.State wifiState = null;
            NetworkInfo.State mobileState = null;

            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
            mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();

            Log.e(TAG,"网络改变(NetworkChangeReceiver)"+"wifi状态:" + wifiState + "\n mobile状态:" + mobileState);

            if (wifiState != null && mobileState != null
                    && NetworkInfo.State.CONNECTED != wifiState
                    && NetworkInfo.State.CONNECTED == mobileState) {// 手机网络连接成功
                Log.e(TAG,"网络改变(NetworkChangeReceiver)"+"手机2g/3g/4g网络连接成功");

                Const.NETWORK_MOD = 2;

            } else if (wifiState != null && NetworkInfo.State.CONNECTED == wifiState) {// 无线网络连接成功
                Log.e(TAG,"网络改变(NetworkChangeReceiver)"+"无线网络连接成功");

                Const.NETWORK_MOD = 2;

            } else if (wifiState != null && mobileState != null
                    && NetworkInfo.State.CONNECTED != wifiState
                    && NetworkInfo.State.CONNECTED != mobileState) {// 手机没有任何的网络
                Log.e(TAG,"网络改变(NetworkChangeReceiver)"+"手机没有任何的网络");

                Const.NETWORK_MOD = 0;

            }

        }

    }
    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        dbHelper = DefaultDBHelper.getInstance(context);

        //初始化日志
        StorageUtil.init(context,null);
        String path = StorageUtil.getDirectoryByDirType(StorageType.TYPE_LOG);
        LogUtil.init(path, Log.DEBUG);


        NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(networkChangeReceiver,intentFilter);
    }


}
